package com.wayz.controller;

import com.wayz.entity.dto.user.LoginDto;
import com.wayz.exception.WayzException;
import com.wayz.response.WayzResponse;
import com.wayz.service.UserAdminService;
import com.wayz.util.IPAddressHelper;
import com.wayz.validator.ParameterValidator;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 鉴权控制器类
 * 
 * @author yinjy
 *
 */
@Controller
@RequestMapping("/authority")
@SessionAttributes("myId")
public class AuthorityController {

	/** 鉴权代理 */
	@Reference(version = "1.0.0", check=false)
	private UserAdminService userAdminService = null;

	/**
	 * 获取验证码
	 * 
	 * @return 字节数组
	 * @throws WayzException 健身馆异常
	 */
	@ResponseBody
	@RequestMapping(value = "/getAuthcode", method = { RequestMethod.GET, RequestMethod.POST }, produces = "image/jpeg")
	public byte[] getAuthcode(HttpServletRequest request) throws WayzException {
		// 调用接口
		String sessionId = request.getSession().getId();
		// 返回应答
		return userAdminService.getAuthcode(sessionId);
	}

	/**
	 * 登录
	 *
	 * @param request HTTP服务请求
	 * @throws WayzException 云歌广告平台异常
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public WayzResponse login(LoginDto loginDto, HttpServletRequest request)
			throws WayzException {
		// 初始化
		WayzResponse response = new WayzResponse();

		// 验证参数
		// 验证参数: 用户名称
		ParameterValidator.notNull(loginDto.getUsername(), "用户名称");
		ParameterValidator.stringLengthLimit(loginDto.getUsername(), "用户名称", 50);
		// 调用接口
		String sessionId = request.getSession().getId();
		loginDto.setSessionId(sessionId);
		loginDto.setIpAddress(IPAddressHelper.getRemoteIPAddress(request));
		response.setData(userAdminService.login(loginDto));

		// 返回应答
		return response;
	}
}
